// src/pages/catering/orderList/OrderList.js
import getIn from '../../../../yali-sdk/utils/getIn';
import {
  ORDER_TYPE_UNPAID, // 待支付
  ORDER_TYPE_PAID, // 配餐中（堂食）接单（外卖）
  ORDER_TYPE_SHIPPED , // 配送中
  ORDER_TYPE_COMPLETED , // 已完成
  ORDER_TYPE_CANCELED , // 已取消
  ORDER_TYPE_CLOSED , // 已关闭
  ORDER_TYPE_AFTERMARKETING , // 售后中 
  ORDER_TYPE_PENDING, // 待接单
  ORDER_TYPE_CATERING, // 餐饮
  ORDER_TYPE_HOTEL, // 酒店
  ORDER_TYPE_OTHER, // 其他
  } from '../../../../yali-sdk/business/order/constrants.js';
import { noOrderListImg } from '../../../../yali-sdk/business/catering/constrants.js';
import fetchOrderList from '../../../../yali-sdk/business/catering/fetchOrderList.js';
import fetchUpdateOrder from '../../../../yali-sdk/business/order/fetchUpdateOrder.js';
import { addNotifier, removeNotifier, notify } from '../../../../yali-sdk/utils/NotifyRegistryCenter';
import { SUCCESS } from '../../../../yali-sdk/utils/success';
import { FAIL } from '../../../../yali-sdk/utils/fail';
import { updateVariableParams, showFail, getImagePath, showSuccess } from '../../../config/common';
import { CATERING_ORDER_DETAIL, CATERINNG_GOODS_LIST, CATERING_SHOP_COMMENT } from '../../pathUrl';
import { wxPay } from '../../../common/wxPayOrder';
import config from '../../../config';
import { getLocalTime } from '../../../config/dateTools';
const cateringMenu = [
  { name: '全部', status: -1 }, 
  { name: '待支付', status: ORDER_TYPE_UNPAID }, 
  { name: '待接单', status: ORDER_TYPE_PAID }, 
  { name: '配餐中', status: ORDER_TYPE_PENDING }, 
  { name: '配送中', status: ORDER_TYPE_SHIPPED }, 
  { name: '已完成', status: ORDER_TYPE_COMPLETED }, 
  { name: '已取消', status: ORDER_TYPE_CANCELED },
  { name: '已关闭', status: ORDER_TYPE_CLOSED }
  ];
const hotelMenu = [
  { name: '全部', status: -1 }, 
  { name: '待支付', status: ORDER_TYPE_UNPAID }, 
  { name: '待确认', status: ORDER_TYPE_PAID }, 
  { name: '已确认', status: ORDER_TYPE_SHIPPED }, 
  { name: '已完成', status: ORDER_TYPE_COMPLETED }, 
  { name: '已取消', status: ORDER_TYPE_CANCELED }, 
  { name: '已关闭', status: ORDER_TYPE_CLOSED }
  ];
const otherMenu = [
  { name: '全部', status: -1 },
  { name: '待支付', status: ORDER_TYPE_UNPAID },
  { name: '待发货', status: ORDER_TYPE_PAID },
  { name: '已发货', status: ORDER_TYPE_SHIPPED },
  { name: '已完成', status: ORDER_TYPE_COMPLETED },
  { name: '已取消', status: ORDER_TYPE_CANCELED },
  { name: '已关闭', status: ORDER_TYPE_CLOSED }
]
Page({

  /**
   * 页面的初始数据
   */
  data: {
    menuItems: hotelMenu,
    currentIndex: 0,
    params: {
      page: 1,
      rows: 5,
      shop_template: ORDER_TYPE_HOTEL,
    },
    orderList: [],
    ORDER_TYPE_UNPAID, // 待支付
    ORDER_TYPE_PAID, // 待接单
    ORDER_TYPE_SHIPPED, // 配送中
    ORDER_TYPE_COMPLETED, // 已完成
    ORDER_TYPE_CANCELED, // 已取消
    ORDER_TYPE_CLOSED, // 已关闭
    ORDER_TYPE_AFTERMARKETING, // 售后中 
    ORDER_TYPE_PENDING, // 待接单
    ORDER_TYPE_CATERING,
    ORDER_TYPE_HOTEL,
    ORDER_TYPE_OTHER,
    ORDER_TYPE_OTHER,
    noOrderListImg,
    listFooterTitle: '',
    loading: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad (options) {
    setTimeout(() => { this.setData({ refresh: true }) }, 800);
    setTimeout(() => { this.setData({ refresh: false }) }, 8000);
    this.onRefresh()
    addNotifier('updateOrderList', () => { this.onPullDownRefresh() }, this);
  },
  onUnload() {
    removeNotifier('updateOrderList');
  },
  onRefresh() {
    if (this.data.loading) return;
    const token = getIn(getApp(), ['globalData', 'token']);
    const status = this.data.menuItems[this.data.currentIndex].status;
    const shop_template = getIn(this.options, ['shop_template']);
    this.data.params = shop_template != undefined ? { ...this.data.params, shop_template } : this.data.params;
    const params = this.data.currentIndex == 0 ? { ...this.data.params, token } : { token, ...this.data.params, status };
    wx.showLoading();
    this.setData({ loading: true, 'params.shop_template': this.data.params.shop_template });
    global.ActionDispatcher.execute(fetchOrderList, params, (code, res) => {
      if (code == SUCCESS) {
        const total = getIn(res.data, ['total']);
        let orderList = getIn(res.data, ['list']);
        orderList = orderList && orderList.map((x) => {
          x.statusText = this.statusText(x.status, x.template);
          return x
        })
        orderList = params.page == 1 ? orderList : this.data.orderList.concat(orderList);
        this.setData({ orderList, total, listFooterTitle: orderList.length < total ? '加载更多' : '已加载完成', loading: false });
        wx.stopPullDownRefresh();
        wx.hideLoading();
      } else if (status == FAIL) {
        wx.stopPullDownRefresh();
        wx.hideLoading()
        this.setData({ loading: false })
      }
    })
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh () {
    const page = 1;
    const params = updateVariableParams(this.data.params, { page });
    this.data.params = params;
    this.onRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom () {
    const { total, orderList } = this.data;
    if (orderList.length < total) {
      // 界面加载完, 且还有下一页的情况。
      const pages = getIn(this.data, ['params', 'page']) || 1;
      const params = updateVariableParams(this.data.params, { page: pages + 1 });
      this.data.params = params;
      this.onRefresh();
    }
  },
  // 状态名称
  statusText(type, template) {
    let text = '';
    switch(type) {
      case ORDER_TYPE_UNPAID: {
        text = '待支付';
        break;
      }
      case ORDER_TYPE_PAID: {
        text = template == ORDER_TYPE_CATERING ? '待接单' : template == ORDER_TYPE_HOTEL ? '待确认' : '待发货';
        break;
      } 
      case ORDER_TYPE_SHIPPED: {
        text = template == ORDER_TYPE_CATERING ? '配送中' : template == ORDER_TYPE_HOTEL ? '已确认' : '已发货';
        break;
      } 
      case ORDER_TYPE_PENDING: {
        text = '配餐中';
        break;
      } 
      case ORDER_TYPE_COMPLETED: {
        text = '已完成';
        break;
      } 
      case ORDER_TYPE_CANCELED: {
        text = '已取消';
        break;
      } 
      case ORDER_TYPE_CLOSED: {
        text = '已关闭';
        break;
      } 
      case ORDER_TYPE_AFTERMARKETING: {
        text = '售后中'
        break;
      }
    }
    return text;
  },
  // 选择店铺类型
  onSelectType(e) {
    const { order_type } = this.data.params;
    const shop_template = getIn(e.currentTarget, ['dataset', 'type']);
    const params = updateVariableParams(this.data.params, { page: 1, shop_template });
    this.data.params = params;
    let menuItems = []
    switch (shop_template){
      case ORDER_TYPE_HOTEL: menuItems = hotelMenu;
      break;
      case ORDER_TYPE_CATERING: menuItems = cateringMenu;
      break;
      default: menuItems = otherMenu;
    }
    this.onRefresh();
    this.setData({ 'params.shop_template': shop_template, currentIndex: 0, menuItems });
  },
  // 选择订单状态回调
  menuCallBackAction(e) {
    const index = getIn(e, ['detail']);
    this.setData({
      currentIndex: index,
    });
    this.onPullDownRefresh();
  },
  // 跳转订单详情
  toOrderDetail(e) {
    const order_id = getIn(e.currentTarget, ['dataset', 'order_id']);
    const shop_id = getIn(e.currentTarget, ['dataset', 'shop_id']);
    const queryString = `order_id=${order_id}&shop_id=${shop_id}`;
    global.navigateHelper && global.navigateHelper.navigateTo && global.navigateHelper.navigateTo({ pathname: CATERING_ORDER_DETAIL, queryString });
  },
  // 跳转产品列表
  toGoodsList(e) {
    const type = getIn(e.currentTaget, ['dataset', 'tyep']);
    const table_no = getIn(e.currentTaget, ['dataset', 'table_no']);
    const queryString = `table_no=${table_no}&type=${type}`;
    global.navigateHelper && global.navigateHelper.navigateTo && global.navigateHelper.navigateTo({ pathname: CATERINNG_GOODS_LIST, queryString });
  },
  // 立即付款
  pay(e) {
    const token = getIn(getApp(), ['globalData', 'token']);
    const openid = getIn(getApp(), ['globalData', 'openid']);
    const order_id = getIn(e.currentTarget, ['dataset', 'order_id']);
    const pay_way = 2;
    const trade_type = 'JSAPI';
    const domain = getIn(config, ['domain']);
    const queryString = `order_id=${order_id}`;
    const payParams = {
      token, order_id, pay_way, trade_type, domain, openid,
    };
    wxPay(payParams, (status, result) => {
      if (status == SUCCESS) {
        showSuccess('支付成功');
        this.onPullDownRefresh();
      } else if (status == 'PAY_FAIL') {
        showFail('支付失败');
      } else if (status == FAIL) {
        showFail(result && result.msg);
      }
    });
  },
  // 取消订单
  cancel(e) {
    const token = getIn(getApp(), ['globalData', 'token']);
    const id = getIn(e.currentTarget, ['dataset', 'order_id']);
    const shop_id = getIn(e.currentTarget, ['dataset', 'shop_id']);
    wx.showModal({
      title: '确定取消订单？',
      success:(res) => {
        if (res.confirm) {
          global.ActionDispatcher.execute(fetchUpdateOrder, { token, id, shop_id, status: ORDER_TYPE_CANCELED }, (code, res) => {
            if (code == SUCCESS) {
              showSuccess('取消成功');
              this.onPullDownRefresh();
            } else if (code == FAIL) {
              showFail('取消失败');
            }
          });
        }
      }
    })
  },
  // 跳转评价页面
  toComment(e) {
    const order_id = getIn(e.currentTarget, ['dataset', 'order_id']);
    const is_comment = getIn(e.currentTarget, ['dataset', 'is_comment']);
    const shop_id = getIn(e.currentTarget, ['dataset', 'shop_id']);
    const queryString = `order_id=${order_id}&is_comment=${is_comment}&shop_id=${shop_id}`;
    global.navigateHelper && global.navigateHelper.navigateTo && global.navigateHelper.navigateTo({ pathname: CATERING_SHOP_COMMENT, queryString });
  }
})